package pyrachnid.view.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import Tools.ScenarConverterXML;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import pyrachnid.ctrl.Simulator;
import pyrachnid.model.robot_model.Manager;
import pyrachnid.model.scenar_model.Scenario;
import pyrachnid.view.MainWindow.EnumMenuItemName;
import pyrachnid.view.component.ScenarFileChooser;

public class MenuItemListener implements ActionListener {

	private Simulator _simulator;
	private String _name;

	public MenuItemListener(Simulator p_sim, String name){
		_simulator = p_sim;
		_name = name;
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		EnumMenuItemName enumItem = null ;
		for(EnumMenuItemName menuItem : EnumMenuItemName.values()){
			if(menuItem.getItemName().equals(_name)){
				enumItem = menuItem;
			}
		}
		switch(enumItem){
			case NEW_SCENAR:
				_simulator.createScenar();
				break;
			case QUIT:
				System.exit(0);
				break;
			case LOAD_SCENAR:
				loadScenar(new ScenarFileChooser());
				break;
			case SAVE_SCENAR:
				saveScenar(new ScenarFileChooser());				     
				break;
			case STATS_VIEW:
				_simulator.displayStatsView();
				break;
		}
	}

	private void loadScenar(ScenarFileChooser sfc) {
		if( sfc.showOpenDialog(_simulator.getMainWindow()) == JFileChooser.APPROVE_OPTION){
			XStream xstream = new XStream(new DomDriver());
			xstream.registerConverter(new ScenarConverterXML(xstream,_simulator));
			Scenario scenar = (Scenario) xstream.fromXML(sfc.getSelectedFile());
			_simulator.loadScenar(scenar);
		}
	}

	private void saveScenar(ScenarFileChooser sfc) {
		if( sfc.showSaveDialog(_simulator.getMainWindow()) == JFileChooser.APPROVE_OPTION){
			XStream xstream = new XStream(new DomDriver());
			xstream.registerConverter(new ScenarConverterXML(xstream,_simulator));
			String scenarXML = xstream.toXML(_simulator.getSenario());
			FileWriter writer = null;
			try {
				writer = new FileWriter(sfc.getSelectedFile(), false);
				writer.write(scenarXML);
			    writer.close();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(sfc, "An error occured while saving the file!\n Do you have writing access to this directory ? ", "I/O Error", JOptionPane.ERROR_MESSAGE);
			}
				Manager manager = Manager.getInstance();
				manager.setMap(_simulator.getSenario().getMap());
				manager.setRobot(_simulator.getSenario().getRobotList());
				manager.setScenario(_simulator.getSenario());
				_simulator.setInitialScenar(_simulator.getSenario());
				_simulator.reInit();
		}
	}
}
